package com.ishare.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ishare.admin.mapper.SysUserMapper;
import com.ishare.admin.mapper.SysUserTokenMapper;
import com.ishare.admin.service.ShiroService;
import com.ishare.admin.service.SysMenuService;
import com.ishare.admin.service.SysUserService;
import com.ishare.admin.service.SysUserTokenService;
import com.ishare.common.constant.Constant;
import com.ishare.common.entity.po.SysMenu;
import com.ishare.common.entity.po.SysUser;
import com.ishare.common.entity.po.SysUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN) {
            //List<SysMenu> menuList = sysMenuDao.selectList(null);
            List<SysMenu> menuList = sysMenuService.selectList();
            permsList = new ArrayList<>(menuList.size());
            for (SysMenu menu : menuList) {
                permsList.add(menu.getPermission());
            }
        } else {
            permsList = sysUserService.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserToken queryByToken(String token) {
        return sysUserTokenService.queryByToken(token);
    }

    @Override
    public SysUser queryUser(Long userId) {
        return sysUserService.selectById(userId);
    }
}
